//
//  BySearchBar.m
//  Homept_ios
//
//  Created by pro on 16/8/24.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "BySearchBar.h"

@implementation BySearchBar

#pragma mark - getter
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:self.bounds];
        _searchBar.delegate = self;
        _searchBar.layer.cornerRadius = 4;
        _searchBar.layer.masksToBounds = YES;
        [_searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];
        [_searchBar.layer setBorderWidth:8];
        
        // 在未输入文字时显示的标识字符
        _searchBar.placeholder = @"请输入要搜索的小区/房源";
        
    }
    return _searchBar;
}

#pragma mark - setter 
// 自定义搜索图片
- (void)setSearchImageName:(NSString *)searchImageName {
    _searchImageName = searchImageName;
    [self.searchBar setImage:[UIImage imageNamed:_searchImageName] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
}

#pragma mark - init
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.layer.borderWidth = 1;
        self.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1].CGColor;
        self.layer.cornerRadius = 4;
        self.backgroundColor = [UIColor clearColor];
        
        if (frame.size.height > 30) {
            self.height = 30;
        }
        [self initSubviews];
    }
    return self;
}

- (void)initSubviews {
    
    [self addSubview:self.searchBar];
    
    [self setSearchImageName:@"sousuo"];
}


#pragma mark - searchBar delegate
// 搜索框将要开始编辑
-(BOOL) searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    return YES;
}
// 搜索框已经开始编辑
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
}
// 搜索框将要结束编辑
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}
// 搜索框已经结束编辑
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
}
// 搜索框内容改变
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//    NSLog(@"输入框的总文本:%@", searchText);
    if (self.textDidChange) {
        self.textDidChange(searchText);
    }
}
// 搜索内容改变，并知道改变的内容范围和代替文本
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//    NSLog(@"将要改变的范围:%@", NSStringFromRange(range));
//    NSLog(@"将要改变改变的内容的替代文本:%@", text);
    return YES;
}
// 点击了搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    if (self.textDidSearch) {
        self.textDidSearch(searchBar.text);
    }
}

@end
